//
//  JWAnimator.m
//  wolf3d
//
//  Created by James Weatherley on 06/12/2009.
//  Copyright 2009 James Weatherley. All rights reserved.
//

#import "JWAnimator.h"
#import "JWRobot.h"
#import "../wolfiphone.h"
#import "../iphone/wolf3dAppDelegate.h"
#import "../iphone/EAGLView.h"

#import <QuartzCore/CADisplayLink.h>

static JWAnimator* animator = 0;

@implementation JWAnimator

@synthesize animationFrames;


-(id)init
{
	assert(!animator);
	animationFrames = 0;
	return [super init];
}

+(JWAnimator*)animator
{
	if(!animator) {
		animator = [[JWAnimator alloc] init];
	}
	return animator;
}

#pragma mark Animations
-(void)setTargetX:(float)x y:(float)y z:(float)z
{
	targetX = x;
	targetY = y;
	targetZ = -z;
	
	robot = nil;
	absorbOnArrival = YES;
	[self calculateAnimationFrames];
	
	deltaX = (targetX - Player.position.origin[0]) / (float)animationFrames;
	deltaZ = (targetZ - Player.position.origin[1]) / (float)animationFrames;
	deltaY = (targetY - Player.position.height) / (float)animationFrames;
	
	deltaAngle = DEG2FINE(NormalizeAngle(RAD2DEG(atan2(deltaZ, deltaX) + M_PI))) - Player.position.angle;
	deltaAzimuth = RAD2FINE(atan2(deltaY, sqrt(deltaX * deltaX + deltaZ * deltaZ))) - Player.position.azimuth;
	
	deltaAngle /= animationFrames;
	deltaAzimuth /= animationFrames;
}

-(void)uturn
{
	robot = nil;
	absorbOnArrival = NO;
	[self calculateAnimationFrames];
	
	deltaX = deltaY = deltaZ = deltaAzimuth = 0.0f;
	targetX	= Player.position.origin[0];
	targetZ	= Player.position.origin[1];
	targetY = Player.position.height;
	
	deltaAngle = DEG2FINE(180.0f) / animationFrames;
}

-(void)orbit
{
}

-(void)deorbit
{
}

#pragma mark Utility
-(void)calculateAnimationFrames
{
	static double animationTime = 1.0;
	wolf3dAppDelegate* appDelegate = (wolf3dAppDelegate*)[UIApplication sharedApplication].delegate;
	
	// Bit out of place, but we need to do it somewhere.
	[appDelegate hideGameScreen:YES];
	
	CADisplayLink* displayLink = appDelegate.glView.displayLink;
	NSInteger interval = displayLink.frameInterval;
	CFTimeInterval duration = displayLink.duration;
	
	animationFrames = rint(animationTime / (interval * duration));
}

-(void)animate
{
	if(animationFrames) {
		Player.position.origin[0] += deltaX;
		Player.position.origin[1] += deltaZ;
		Player.position.height += deltaY;
		Player.position.angle += deltaAngle;
		Player.position.azimuth += deltaAzimuth;
		
		if(!--animationFrames) {
			Player.position.origin[0] = targetX;
			Player.position.origin[1] = targetZ;
			Player.position.height = targetY;
			wolf3dAppDelegate* appDelegate = (wolf3dAppDelegate*)[UIApplication sharedApplication].delegate;
			
			if(absorbOnArrival) {
				[appDelegate absorb:nil];
				[appDelegate addEntity:robot];
				[robot release];
				robot = nil;
			}
			[appDelegate hideGameScreen:NO];
		}
	}
}

-(void)addOnArrival:(JWRobot*)r
{
	assert(robot == nil);
	robot = r;
	[robot retain];
}


@end
